package org.me.runaway;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.net.URL;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

/**
 * @author RunAway
 */
public class PlaceDetails extends Activity{

    private static final String METHOD_NAME="votePlace";
    private static final String ACTION="votePlace";

    private static final String RETURN_OPTION = "Voltar para o inicio";
    private static final String FAVORITE_OPTION = "Adicionar aos Favoritos";
    private long id;

    Intent back;
    Intent List;

    TextView t1;
    TextView t2;
    TextView t3;
    TextView t4;
    TextView t5;
    TextView t6;
    TextView t7;
    ImageView i1;
    ImageView i2;
    Button good;
    Button bad;

    Drawable image;
    boolean favorited, voted, ok;

    Bundle extras;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.details);


        extras = new Bundle();
        extras = getIntent().getExtras();

        if (extras != null){

            i1 = (ImageView) findViewById(R.id.image);
            t1 = (TextView) findViewById(R.id.name);
            t2 = (TextView) findViewById(R.id.type);
            t3 = (TextView) findViewById(R.id.details);
            t4 = (TextView) findViewById(R.id.address);
            t5 = (TextView) findViewById(R.id.contacts);
            t6 = (TextView) findViewById(R.id.schedule);
            t7 = (TextView) findViewById(R.id.rate);
            i2 = (ImageView) findViewById(R.id.price);

            id = extras.getLong(Place.KEY_ROWID);

            image = LoadImageFromWebOperations(extras.getString(Place.KEY_IMAGE));
            if (image == null)
                i1.setImageResource(R.drawable.noimage);
            else
                i1.setImageDrawable(image);
            i1.setScaleType(ImageView.ScaleType.FIT_XY);
            t1.setText(extras.getString(Place.KEY_NAME));
            t2.setText(extras.getString(Place.KEY_TYPE));
            t3.setText(extras.getString(Place.KEY_DETAILS));
            t4.setText(extras.getString(Place.KEY_ADDRESS));
            t5.setText(extras.getString(Place.KEY_CONTACT1) +"\n"+ extras.getString(Place.KEY_CONTACT2));
            t6.setText(extras.getString(Place.KEY_SCHEDULE));
            t7.setText(extras.getString(Place.KEY_RATE) + " (Gosto/ Não Gosto)");
            favorited = Boolean.parseBoolean(extras.getString(Place.KEY_FAVORITE));
            voted = Boolean.parseBoolean(extras.getString(Place.KEY_VOTED));

            String i = extras.getString(Place.KEY_PRICE);
            if (i.equals("1"))
                i2.setImageResource(R.drawable.euro1);
            else if (i.equals("2"))
                i2.setImageResource(R.drawable.euro2);
            else if (i.equals("3"))
                i2.setImageResource(R.drawable.euro3);   

            good = (Button) findViewById(R.id.good);
            bad = (Button) findViewById(R.id.bad);

            changeButtons();

            good.setOnClickListener(new View.OnClickListener(){
                 public void onClick(View v){
                    DB_Adapter db = new DB_Adapter(getBaseContext());
                    Place p;
                    db.open();
                    Cursor cs;

                    if (voted == false){
                        ok = ratePlace("good");

                        if (ok){
                            cs = db.getPlaceID(id);

                            if (cs != null){
                                cs.moveToFirst();
                                p = db.getPlaceFromCursor(cs);
                                t7.setText(p.getRate() + " (Gosto/ Não Gosto)");
                                changeButtons();
                                db.close();
                            }
                        }
                        else
                            Toast.makeText(getBaseContext(), "ERRO: Não foi possível efectuar a votação\nTente mais tarde", Toast.LENGTH_SHORT).show();

                        db.close();
                    }
                 }
            });

            bad.setOnClickListener(new View.OnClickListener(){
                 public void onClick(View v){
                    DB_Adapter db = new DB_Adapter(getBaseContext());
                    Place p;
                    db.open();
                    Cursor cs;

                    if (voted == false){
                        ok = ratePlace("bad");

                        if(ok){
                            cs = db.getPlaceID(id);

                            if (cs != null){
                                cs.moveToFirst();
                                p = db.getPlaceFromCursor(cs);
                                t7.setText(p.getRate() + " (Gosto/ Não Gosto)");
                                changeButtons();
                                db.close();
                            }
                        }
                        else
                            Toast.makeText(getBaseContext(), "ERRO: Não foi possível efectuar a votação\nTente mais tarde", Toast.LENGTH_SHORT).show();

                        db.close();
                    }
                 }
            });

        }
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, RETURN_OPTION).setIcon(R.drawable.undo);
        menu.add(0, 1, 0, FAVORITE_OPTION).setIcon(R.drawable.favoriteadd);
        menu.add(0, 2, 0, MainActivity.EXIT_OPTION).setIcon(R.drawable.logout);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                back = new Intent(this, MainActivity.class);
                back.putExtra("id", "myLocation");
                startActivity(back);
                this.finish();
                return true;
            case 1:
                if (favorited == false){
                    boolean ok = addFavorites();
                    if (ok == true){
                        Toast.makeText(this, "Adicionado aos Favoritos", Toast.LENGTH_SHORT).show();
                        List = new Intent(this, PlaceList.class);
                        List.putExtra("favorites", true);
                        startActivity(List);
                        this.finish();
                    }
                    else
                        Toast.makeText(this, "ERRO: Não foi adicionado aos Favoritos", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(this, "ERRO: Já foi adicionado aos favoritos", Toast.LENGTH_SHORT).show();
                }
                return true;
            case 2:
                this.finish();
                return true;
        }

        return false;
    }

    private boolean addFavorites(){
        Place p = new Place();
        DB_Adapter db = new DB_Adapter(getBaseContext());
        db.open();
        Cursor cs;
        
        try{
            cs = db.getPlaceID(id);

            if (cs != null){
                p = db.getPlaceFromCursor(cs);

                p.setFavorite(true);

                db.updatePlace(id, p);
                db.close();
                return true;
            }
        }
        catch (Exception e){
            db.close();
            return false;
        }

        db.close();
        return false;
    }

    private boolean ratePlace(String rate){
        Place p = new Place();
        DB_Adapter db = new DB_Adapter(getBaseContext());
        int g = 0, b = 0;
        String[] rates;
        boolean status = false;

        SoapObject request;
        SoapSerializationEnvelope soapEnvelope;

        request = new SoapObject(MainActivity.NAMESPACE, METHOD_NAME);
        soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        HttpTransportSE aht = new HttpTransportSE(MainActivity.URL);

        db.open();
        Cursor cs = db.getPlaceID(id);

        if (cs != null){
            cs.moveToFirst();
            p = db.getPlaceFromCursor(cs);
            if (p.getRate().length() > 0){
                rates = p.getRate().split("/");
                g = Integer.parseInt(rates[0]);
                b = Integer.parseInt(rates[1]);
            }
            if (rate.equals("good")){
                g++;
                request.addProperty("name", p.getName());
                request.addProperty("rate", "good");
            }
            else if (rate.equals("bad")){
                b++;
                request.addProperty("name", p.getName());
                request.addProperty("rate", "bad");
            }

            p.setRate(g+"/"+b);
            p.setVoted(true);
            voted = true;

            try{
                soapEnvelope.setOutputSoapObject(request);
                aht.call(ACTION, soapEnvelope);
                SoapObject result = (SoapObject) soapEnvelope.bodyIn;
                if (result.getPropertyCount() > 0){
                    status = Boolean.valueOf(result.getProperty(0).toString());
                    if (status)
                        db.updatePlace(id, p);

                    db.close();
                    return true;
                }
                else{
                    db.close();
                    return false;
                }
            }
            catch(Exception e){
                db.close();
                return false;
            }
        }
        else
            return false;
    }

    public void changeButtons(){
        if (voted == true){
            good.setVisibility(4);
            bad.setVisibility(4);
        }
        else{
            good.setVisibility(0);
            bad.setVisibility(0);
        }
    }

    private Drawable LoadImageFromWebOperations(String url)
    {
        try{
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }
        catch (Exception e) {
            return null;
        }
    }

}
